package com.crm.web.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.Servlet;

import org.apache.struts2.ServletActionContext;

import com.crm.domain.User;
import com.crm.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

public class UserAction extends ActionSupport implements ModelDriven<User> {

	private User user = new User();
	
	@Override
	public User getModel() {
		return user;
	}

	// 注入Service
	private UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	// 用户注册
	public String regist(){
		userService.regist(user);
	
		return LOGIN;
	}
	
	// 用户登录
	public String login(){
		// 调用Service，判断用户的账号密码是否正确
		User existUser = userService.login(user);
		// 根据结果跳转到不同的页面
		if(null == existUser){
			this.addActionError("用户名或密码错误");
			return LOGIN;
		}else{
			ActionContext.getContext().getSession().put("existUser", existUser);
			return SUCCESS;
			
		}
		
	}
	
	// 客户拜访记录-添加客户拜访记录-查询所有用户
	public String findAllUser() throws IOException{
		// 1. 查询所有用户
		List<User> list = userService.findAllUser();
		// 2. 将list转成json
		JSONArray jsonArray = JSONArray.fromObject(list);
		ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
		ServletActionContext.getResponse().getWriter().write(jsonArray.toString());
		return NONE;
	}
	
	
	
}
